package com.eonmind.ai.service.impl;

import com.eonmind.ai.converts.AiBiConvert;
import com.eonmind.ai.dto.AiBiDto;
import com.eonmind.ai.mapper.AiUserModelConsumeHistoryMapper;
import com.eonmind.ai.service.IAiBiService;
import com.eonmind.common.provider.entity.ai.AiUserModelConsumeHistory;
import com.eonmind.user.contract.dto.UserInfoData;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.dev33.satoken.SaManager.log;
import static com.eonmind.common.contract.constants.ai.AiConstant.AI_CONSUME_HISTORY_REDIS_KEY;

/**
 * @author Xujie
 * @since 2025/5/29 21:22
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class AiBiService implements IAiBiService {
    private final AiUserModelConsumeHistoryMapper aiUserModelConsumeHistoryMapper;
    private final RedissonClient redissonClient;

    @Async("aiDefaultTaskExecutor")
    public void updateUserConsumeHistory(Long userId, Long chatConsumeCount, Long DrawConsumeCount, Long VideoConsumeCount, String dateString) {
        String lockKey = AI_CONSUME_HISTORY_REDIS_KEY + userId;
        DateTime today = DateTime.now();
        String todayString = today.toString("yyyy-MM-dd");
        if (StringUtils.isNoneBlank(dateString)) {
            todayString = dateString;
        }
        RLock lock = redissonClient.getLock(lockKey);
        boolean success = false;
        try {
            success = lock.tryLock(10, TimeUnit.SECONDS);
            if (success) {
                AiUserModelConsumeHistory aiUserModelConsumeHistory =
                        aiUserModelConsumeHistoryMapper.selectByUserIdAndDate(userId, todayString);
                if (ObjectUtils.isEmpty(aiUserModelConsumeHistory)) {
                    aiUserModelConsumeHistory = new AiUserModelConsumeHistory();
                    aiUserModelConsumeHistory.setUserId(userId);
                    aiUserModelConsumeHistory.setDataDate(todayString);
                    aiUserModelConsumeHistory.setChatConsumeCount(chatConsumeCount);
                    aiUserModelConsumeHistory.setDrawConsumeCount(DrawConsumeCount);
                    aiUserModelConsumeHistory.setVideoConsumeCount(VideoConsumeCount);
                } else {
                    aiUserModelConsumeHistory.setChatConsumeCount(aiUserModelConsumeHistory.getChatConsumeCount() + chatConsumeCount);
                    aiUserModelConsumeHistory.setDrawConsumeCount(aiUserModelConsumeHistory.getDrawConsumeCount() + DrawConsumeCount);
                    aiUserModelConsumeHistory.setVideoConsumeCount(aiUserModelConsumeHistory.getVideoConsumeCount() + VideoConsumeCount);
                }
                aiUserModelConsumeHistoryMapper.saveOrUpdate(aiUserModelConsumeHistory);
            }
        } catch (InterruptedException e) {
            log.error("获取锁失败：{}", e.getMessage());
        } finally {
            if (success) {
                lock.unlock();
            }
        }


    }

    @Override
    public List<AiBiDto.UserConsumeData> getUserConsumeData(UserInfoData userInfoData, AiBiDto.UserConsumeDataRequest request) {
        if (ObjectUtils.isEmpty(userInfoData) || ObjectUtils.isEmpty(request)) {
            return List.of();
        }
        DateTime today = DateTime.now();
        DateTime startTime = today.minusDays(request.getDayCount());
        String todayString = today.toString("yyyy-MM-dd");
        String startString = startTime.toString("yyyy-MM-dd");
        List<AiUserModelConsumeHistory> aiUserModelConsumeHistoryList
                = aiUserModelConsumeHistoryMapper.selectByDate(startString, todayString, userInfoData.getId());
        return AiBiConvert.toUserConsumeDataList(aiUserModelConsumeHistoryList);
    }
}
